import Notify from '@vant/weapp/notify/notify';
const app = getApp();
const $api = require('../../utils/api.js').API;
const { $Toast } = require('../../dist/base/index');
Page({
    data: {
        contact: '',
        title: '',
        price: 0,
        task_time: '',
        note: '',

        fileList: [],
        array: ['快递', '购物', '其他'],
        index: 0,
    },

    onLoad() {
        this.getContect()
    },

    // 获取联系方式
    getContect() {
        $api.getUserinfo({ openid: app.globalData.openid })
            .then(res => {
                let contact = res.data.data[0].contact
                this.setData({ contact })
            })
    },

    // 发布
    submit() {
        console.log(this.data.fileList)
        let fileList = []
        for (let i = 0; i < this.data.fileList.length; i++) {
            let url = this.data.fileList[i].url
            let index = url.lastIndexOf('/')
            url = url.slice(index + 1)
            console.log(url)
            fileList.push(url)
        }
        let params = {
            price: this.data.price,
            title: this.data.title,
            type: this.data.index,
            picture: fileList,
            openid: app.globalData.openid,
            note: this.data.note,
            task_time: this.data.task_time,
        }
        console.log(params)
        $api.addOrder(params)
            .then(res => {
                console.log(res)
                $Toast({
                    content: '发布成功',
                    type: 'success',
                    duration: 2000
                });
                wx.switchTab({
                    url: '/pages/home/home',
                });
            })
    },

    // 类型选择器
    bindPickerChange(e) {
        console.log(e.detail.value)
        this.setData({
            index: e.detail.value
        })
    },

    // 输入框内容变动
    onChange(e) {
        let attri = e.target.dataset.attri
        this.setData({
            [attri]: e.detail
        })
    },

    // 上传图片
    afterRead(e) {
        let _this = this
        const { file } = e.detail;
        // console.log(file)
        wx.uploadFile({
            url: `http://localhost:3000/order/upload`, // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'img',
            formData: {
                type: _this.data.index
            },
            success(res) {
                const { fileList = [] } = _this.data
                fileList.push({ ...file, url: res.data })
                _this.setData({
                    fileList
                })
                console.log(fileList)
            }
        });
    },

    // 删除图片
    deletePic(e) {
        // console.log(e.detail.index)
        let index = e.detail.index
        let fileList = this.data.fileList
        fileList.splice(index, 1)
        this.setData({
            fileList
        })
    },

    // 联系方式提示
    onClickIcon() {
        Notify({ type: 'primary', message: '请在个人信息页完善联系方式' });
    }
})